/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.infrastructure.util;

import cn.hallele.infrastructure.metadata.constant.MsgCodeConst;
import cn.hallele.infrastructure.metadata.exception.children.ServiceCallException;
import cn.hallele.infrastructure.metadata.io.Metric;
import cn.hallele.infrastructure.metadata.io.Response;
import cn.hallele.infrastructure.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/10/5 14:45
 */
@Slf4j
public class OutGoingUtil {
    /**
     * 从 {@link Response}中获取响应，内部微服务调用使用
     *
     * @param r   {@link Response}
     * @param <T> data类型
     * @return data
     */
    public static <T> T getData(Response<T> r) {
        Metric metric = r.getMetric();
        if (ObjectUtil.equals(MsgCodeConst.SUCCESS, metric.getMsgCode())) {
            return r.getData();
        }

        log.error("Service call failed. Error code: {}, msg: {}", metric.getMsgCode(), metric.getMsgDesc());
        throw new ServiceCallException(MsgCodeConst.SERVICE_CALL_ERROR, metric.getMsgCode(), metric.getMsgDesc());
    }
}
